import cv2
import numpy as np

# 尝试读取图片
img = cv2.imread('pic/trafficLight.jpg')

# 检查图片是否成功读取
if img is None:
    print("Error: Could not read the image.")
else:
    # 转换为灰度图像
    gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

    thresh = 127

    kernel_size = 3

    # 自适应阈值处理
    img_seg = cv2.adaptiveThreshold(gray_img, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, kernel_size, 5)

    # 正确使用cv2.imwrite
    cv2.imwrite('img_seg.jpg', img_seg)

    # 显示原始图像和分割后的图像
    cv2.imshow('image', img)
    cv2.imshow('image_seg', img_seg)

    cv2.waitKey(0)
    cv2.destroyAllWindows()
